package com.plugin.sproutcore.core.launch;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.model.ILaunchConfigurationDelegate;

import com.plugin.sproutcore.lang.ProcessFactory;
import com.plugin.sproutcore.ui.launch.SproutCoreMainTab;

/**
 * Launches the sc-server process from the eclipse run command.
 */
public class LaunchConfigurationDelegate implements ILaunchConfigurationDelegate
{

	/**
	 * @see org.eclipse.debug.core.model.ILaunchConfigurationDelegate#launch(org.eclipse.debug.core.ILaunchConfiguration, java.lang.String, org.eclipse.debug.core.ILaunch, org.eclipse.core.runtime.IProgressMonitor)
	 */
	public void launch(ILaunchConfiguration configuration, String mode,
			ILaunch launch, IProgressMonitor monitor) throws CoreException 
	{
		// Ensure that the configuration knows about the custom process factory.
		ILaunchConfigurationWorkingCopy copy = configuration.getWorkingCopy();
		copy.setAttribute(DebugPlugin.ATTR_PROCESS_FACTORY_ID, 
				SproutCoreProcessFactory.PROCESS_FACTORY_ID);
		copy.doSave();
		
		String projectPath = configuration.getAttribute(
				SproutCoreMainTab.PROJECTPATH_ATTR, "");
		IPath path =  Path.fromPortableString(projectPath);
		
		// paths are relative to the workspace
		path = ResourcesPlugin.getWorkspace().getRoot().getLocation().append(path);
		File dir = path.toFile();
		
		List<String> command = new ArrayList<String>();
		command.add("sc-server");
		
		ProcessBuilder builder = ProcessFactory.generate(command, dir);
		try {
			final Process p = builder.start();
			//
			if (p != null) 
			{
				DebugPlugin.newProcess(launch, p, "SproutCore server");
			}
			//
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

}
